package com.zohnblog.web.interceptor;

import com.zohnblog.service.impl.WebStatisticServiceImpl;
import com.zohnblog.utils.Commons;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/*
* 自定义的Interceptor拦截器类，用于封装请求后的数据类到request域中，供html页面使用
* 自定义MVC的Interceptor拦截器类有一下两点注意
* 1.使用@Configuration注解声明
* 2.自定义注册类将自定义的Interceptor拦截器类进行注册使用
* */
@Configuration
public class BaseInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(BaseInterceptor.class);
    @Autowired
    private Commons commons;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //            // 获取当前登录用户
        String uri = request.getRequestURI();
        String ipAddress = request.getRemoteAddr(); // ip地址
        logger.info("正在请求uri:" + uri + " ,ip为:" + ipAddress);

        if(uri.contains("delete") || uri.contains("modify") || uri.contains("ipbanmode/") || uri.contains("/article/publish")) {
            User user=(User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (!"admin".equals(user.getUsername())) {
                logger.info("游客账号无法进行该操作");
                JSONObject res = new JSONObject();
                res.put("success",false);
                res.put("msg","游客账号无法进行该操作");
                response.setHeader("Content-type", "application/json;charset=utf-8");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(res.toString());
                response.flushBuffer();
                return false;
            }
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                            @Nullable ModelAndView modelAndView) throws Exception {
//        logger.info("postHandle:" + request.getRemoteAddr());

        // 用户将封装的Commons工具返回页面
        request.setAttribute("commons",commons);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                 @Nullable Exception ex) throws Exception {
    }
}
